package org.example.postgraduateproject.Servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.postgraduateproject.Dao.QuestionDao;
import org.example.postgraduateproject.Dao.imp.QuestionDaoImp;
import org.example.postgraduateproject.entity.Question;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wu
 * @date 2025-05-28
 * http://localhost:8080/postgraduateProject/question.do?action=list
 */
@WebServlet("/question.do")
public class QuestionServlet extends HttpServlet {
    private QuestionDao questionDao = new QuestionDaoImp();
    private Gson gson = new Gson();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        String action = req.getParameter("action");
        Map<String, Object> result = new HashMap<>();

        try {
            switch (action) {
                case "list":
                    handleList(req, result);
                    break;
                case "get":
                    handleGet(req, result);
                    break;
                case "add":
                    handleAdd(req, result);
                    break;
                case "update":
                    handleUpdate(req, result);
                    break;
                case "delete":
                    handleDelete(req, result);
                    break;
                default:
                    result.put("success", false);
                    result.put("message", "未知操作类型");
                    result.put("errorCode", 4001);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "服务器内部错误");
            result.put("errorCode", 5000);
        }

        String json = gson.toJson(result);
        out.println(json);
        out.flush();
        out.close();
    }

    private void handleList(HttpServletRequest req, Map<String, Object> result) {
        Integer userId = getIntParameter(req, "userId");
        String status = req.getParameter("status");

        List<Question> questions;
        if (userId != null) {
            questions = questionDao.selectQuestionsByUserId(userId);
        } else if (status != null) {
            questions = questionDao.selectAllQuestions();
        } else {
            questions = questionDao.selectAllQuestions();
        }

        result.put("success", true);
        result.put("message", "查询成功");
        result.put("data", questions);
    }

    private void handleGet(HttpServletRequest req, Map<String, Object> result) {
        Integer questionId = getIntParameter(req, "questionId");
        if (questionId == null) {
            result.put("success", false);
            result.put("message", "缺少参数questionId");
            result.put("errorCode", 4002);
            return;
        }

        Question question = questionDao.selectQuestionById(questionId);
        if (question == null) {
            result.put("success", false);
            result.put("message", "问题不存在");
            result.put("errorCode", 4004);
        } else {
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", question);
        }
    }

    private void handleAdd(HttpServletRequest req, Map<String, Object> result) {
        Integer userId = getIntParameter(req, "userId");
        String title = req.getParameter("title");
        String content = req.getParameter("content");

        if (userId == null || title == null || content == null) {
            result.put("success", false);
            result.put("message", "缺少必要参数");
            result.put("errorCode", 4002);
            return;
        }

        Question question = new Question();
        question.setUserId(userId);
        question.setTitle(title);
        question.setContent(content);
        question.setStatus("active");
        question.setViewCount(0);

        int rows = questionDao.insertQuestion(question);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "问题添加成功");
        } else {
            result.put("success", false);
            result.put("message", "问题添加失败");
            result.put("errorCode", 4005);
        }
    }

    private void handleUpdate(HttpServletRequest req, Map<String, Object> result) {
        Integer questionId = getIntParameter(req, "questionId");
        if (questionId == null) {
            result.put("success", false);
            result.put("message", "缺少参数questionId");
            result.put("errorCode", 4002);
            return;
        }

        Question existingQuestion = questionDao.selectQuestionById(questionId);
        if (existingQuestion == null) {
            result.put("success", false);
            result.put("message", "问题不存在");
            result.put("errorCode", 4004);
            return;
        }

        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String status = req.getParameter("status");

        if (title != null) existingQuestion.setTitle(title);
        if (content != null) existingQuestion.setContent(content);
        if (status != null) existingQuestion.setStatus(status);

        int rows = questionDao.updateQuestion(existingQuestion);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "问题更新成功");
        } else {
            result.put("success", false);
            result.put("message", "问题更新失败");
            result.put("errorCode", 4006);
        }
    }

    private void handleDelete(HttpServletRequest req, Map<String, Object> result) {
        Integer questionId = getIntParameter(req, "questionId");
        if (questionId == null) {
            result.put("success", false);
            result.put("message", "缺少参数questionId");
            result.put("errorCode", 4002);
            return;
        }

        int rows = questionDao.deleteQuestion(questionId);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "问题删除成功");
        } else {
            result.put("success", false);
            result.put("message", "问题删除失败或不存在");
            result.put("errorCode", 4007);
        }
    }

    private Integer getIntParameter(HttpServletRequest req, String paramName) {
        String value = req.getParameter(paramName);
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}